import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from "@src/store/base";
import payBehavior from "@booking/pages/submitBooking/payBehavior";
import { getOrderDetail, getOrderQrcode,pollOrder,checkProtectTime } from "@src/api/booking";
import dayjs from "dayjs";
import { minuteToHour } from "@src/common/dateUtils";
import router from "@src/router";

const statusMap = {
  0: ["未支付", "你的订单已提交，请尽快支付"],
  1: ["待商家确认", "你的订单已提交，请等待系统确认"],
  2: ["待消费", "您的订单已被商家确认，到店请打开以下二维码核销使用"],
  3: ["已消费", "您的订单已到店消费，详细消费情况请查看费用明细"],
  4: ["支付超时", "订单已超过可支付时间，请重新下单"],
  5: ["超时未确认", "您的订单店家没有处理，系统已经关闭订单并退款，如有疑问请联系店家"],
  6: ["用户取消支付", "您未支付且取消了订单"],
  7: ["用户已取消", "您的订单已取消，扣退款情况请查看账单，继续住店请重新下单"],
  8: ["商家已取消", "您的订单已取消，扣退款情况请查看账单，继续住店请重新下单"],
  9: ["已过期", "你的订单已过期，系统已经自动扣除相关费用，如有疑问请联系商家"]
};
Component({
  behaviors: [storeBindingsBehavior, payBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  data: {
    order: null,
    bizData: null,
    statusInfo: null,
    product: null,
    payRule: null,
    payChannels: null,
    refundRule: null,
    shopInfo: null,
    tips: null,
    statusRecords: null,
    refundRecord: null,
    pollTime:'',
    isPoll:false,
  },
  observers:{
    'showQrCode':function(value){
      let {isPoll,order} = this.data
      if(isPoll || order.subStatus===3||order.subStatus===6||order.subStatus===7||order.subStatus===8||order.subStatus===9||order.subStatus===4||order.subStatus===5){
        return
      }
      value?this.startAndClearPoll():this.startAndClearPoll(1)
    }
  },
  methods: {
    onLoad(options) {
      let { orderNo } = options;
      this.setData({ orderNo: orderNo });
    },
    onUnload: function () {
      clearInterval(this.data.pollTime)
    },
    onLogin() {
      this.fetchData();
      this.fetchQrCode();
    },
    onPullDownRefresh() {
      wx.stopPullDownRefresh();
      this.fetchData();
      this.fetchQrCode();
      // 初始化
      this.setData({ showQrCode: false })
    },
    fetchData() {
      getOrderDetail({ orderNo: this.data.orderNo }).then(res => {
        let orderDetail = res.data;
        let tempList = orderDetail.payRule.payChannels.split(",")
        let payChannels = [];
        for (let i = 0; i < tempList.length; i++) {
          if (tempList[i] === '0') {
            payChannels.push("wx")
          } else if (tempList[i] === '1') {
            payChannels.push("balance")
          }
        }
        let product = orderDetail.product
        let bizData = JSON.parse(orderDetail.order.bizData);
        if (bizData) {
          bizData.manyDate = Object.keys(bizData.roomPrices).length
        }
        let periodStartTime = minuteToHour(product.periodStartTime)
        let periodEndTime = minuteToHour(product.periodEndTime);
        let useTips = `${bizData.beginDay} ${periodStartTime} ~ ${periodEndTime === "00:00" ? "24:00" : periodEndTime}`;
        this.setData({
          useTips: useTips,
          order: orderDetail.order,
          bizData: bizData,
          statusInfo: statusMap[orderDetail.order.subStatus],
          product: product,
          payRule: orderDetail.payRule,
          payChannels: payChannels,
          refundRule: orderDetail.refundRule,
          shopInfo: orderDetail.shopInfo,
          tips: orderDetail.tips,
          statusRecords: orderDetail.statusRecords,
          refundRecord: orderDetail.refundRecord
        })
      });

    },
    startAndClearPoll(type){
      const _that = this
      if(!type){
        this.data.pollTime = setInterval(() => {
          pollOrder({orderNo:this.data.orderNo}).then(res=>{
            if(res.code == 0){
              if(res.data.success){
                wx.showModal({
                  title: '提示',
                  content: `您的预定订单${this.data.orderNo}已经在${res.data.shopName}被核销`,
                  showCancel:false,
                  success(res) {
                    if (res.confirm) {
                      // await _that.setData({isPoll:true})
                      // await _that.fetchData();
                      // await clearInterval(_that.data.pollTime)
                      // await _that.setData({showQrCode: false})
                    }
                  }
                  
                })
                _that.setData({isPoll:true})
                _that.fetchData();
                clearInterval(_that.data.pollTime)
                _that.setData({showQrCode: false})
              }
            }
          })
        }, 1000);
      }else{
        clearInterval(this.data.pollTime)
      }
    },
    fetchQrCode() {
      getOrderQrcode({ orderNo: this.data.orderNo }).then(res => {
        this.setData({ qrCode: res.data, showQrCode: false })
      })
    },
    handleShowQrCode() {
      this.setData({ showQrCode: true })
    },
    handleShowPayDetailDialog() {
      this.selectComponent("#payDetailDialog").open();
    },
    handleShowRefundRule() {
      this.selectComponent("#refund-rule-dialog").open();
    },
    handleToBookingDetail() {
      router.push({
        name: 'booking/roomDetail', params: {
          source: "order",
          productNo: this.data.product.productNo,
          endDay: this.data.bizData.endDay,
          beginDay: this.data.bizData.beginDay

        }
      })
    },
    handleHideQrCode() {
      this.setData({ showQrCode: false })
    },
   
    handleToRefundRecord() {
      router.push({
        name: 'booking/orderDetailBillDetail',
        success: (res) => {
          res.eventChannel.emit('order', {
            order: this.data.order,
            refundRecord: this.data.refundRecord
          })
        }
      })
    },

    handleStop() {
      return true;
    },
    handleToPay() {
      let order = this.data.order;
      let data = {
        orderNo: order.orderNo,
        payChannels: this.data.payChannels,
        payFee: order.totalFee - order.discountFee - order.pointsDiscountFee-order.supermemberPointsDiscountFee,
        hasDiscount: order.useDiscount || order.usePointsDiscount
      }
      this.toBookingPay(data).then(res => {
        wx.showToast({ title: "支付成功", icon: "none", duration: 2000 });
        this.fetchData();
      }).catch((error) => {
        console.error("error", error)
        this.fetchData();
      })
    },
    handleCancelOrder() {
      let {orderNo} = this.data
      checkProtectTime({orderNo}).then(res=>{
        if(res.code == 0){
          if(res.data.resCode == 0){
            this.selectComponent("#cancelDialog").open().then(res => {
              wx.nextTick(() => {
                this.fetchData();
              })
            });
          }else{
            wx.showModal({
              title: '提示',
              content:'此订单已超出售后时效，暂不支持取消，请联系商家处理',
              showCancel:false,
              confirmText:'我知道了',
            })
          }
        }
      })
    },
    handleShowStatusRecord() {
      this.selectComponent("#statusDialog").open();
    },

  }
})
